/**
 * 商品大图列表
 */
var React = require('react-native');
var {msg} = require('iflux-native');
var QMMktActivity = require('./mkt-activity');
var QMPullRefreshListView = require('./pull-refresh-list-view');
var QMSwipeRefreshListView = require('./swipe-refresh-list-view');
var QMBtnContainer = require('./button');
var fetch = require('./fetch');
var QMConst = require('./const');

var SCREEN_WIDTH = require('Dimensions').get('window').width;

var {
  StyleSheet,
  View,
  Image,
  StatusBarIOS,
  Text,
  Platform,
  PixelRatio,
  TouchableOpacity,
  TouchableNativeFeedback,
  Navigator
} = React;


//just do nothing.
var noop = () => {};

var RefreshListView = (Platform.OS === 'ios') ? QMPullRefreshListView :
  QMSwipeRefreshListView;

//商品大图列表
var GoodsThumbnailList = React.createClass({

  getDefaultProps() {
    return {
      url: '',
      style: null,
      onDataReceive: noop,
      /*来源，现在就在值为shelf时有特殊操作*/
      source: '',
	    //自定义头部
	    customHeader: noop
    }
  },


  getInitialState() {
    return {
      isVisible: false,
      skuId: '',
      spuId: '',
      markets: [],
      prices: [],
      priceRange: []
    };
  },


  render() {
    return (
      <View style={styles.container}>
        <RefreshListView
          ref='refreshListView'
          url={this.props.url}
          style={this.props.style}
          contentContainerStyle={styles.list}
          onDataReceive={this._hanldDataReceive}
          renderRow={this._renderRow}
          customHeader={this.props.customHeader}
        />
      </View>
    );
  },


  /**
   * 定义每一行
   */
  _renderRow(row, _, index) {
    return (
      <View style={styles.box} key={index} renderToHardwareTextureAndroid={true}>

        <QMBtnContainer  onPress={row.enabled == 0 ? null : this._handleDetail.bind(this, {spuId: row.pid, skuId: row.id})}>
          {this._getImg(row)}
        </QMBtnContainer>

        <View style={styles.detail}>
          <Text style={row.enabled == 0 ? styles.proText_disabled : styles.proText} numberOfLines={2} onPress={row.enabled == 0 ? null : this._handleDetail.bind(this, {spuId: row.pid, skuId: row.id})}>{row['name']}</Text>
          <QMMktActivity data={this.state.markets[index]}/>
          <View style={styles.proCart}>

            {
              row.enabled == 0 ? <Text style={styles.priceText}></Text> :
                <Text style={styles.priceText}>￥{this.state.prices[index] ? this.state.prices[index].toFixed(2) : this.state.priceRange[index]}</Text>
            }

            {
              row.enabled == 0 ?
                <QMBtnContainer
                  style={styles.cartImgContainer}
                  onPress={this.props.onDeleteShelf.bind(this, row.pid)}>
                  <Image style={styles.cart} source={require('img/delete_blue.png')} />
                </QMBtnContainer>
                :
                <QMBtnContainer
                  style={styles.cartImgContainer}
                  onPress={this._handlePress.bind(this, {spuId: row.pid, skuId: row.id})}>
                  <Image style={styles.cart} source={require('img/cart_green.png')} />
                </QMBtnContainer>
            }
          </View>
        </View>
      </View>
    );
  },


  _getImg(row){
    return(
      <View style={styles.imgBorder} >
        {
          row.enabled == 0 ?
            <Image style={styles.img} source={{uri: row['img']}} >
              <View style={styles.imgViewMargin} >
                <View style={styles.imgView} >
                  <Text style={styles.imgViewText}>已失效</Text>
                </View>
              </View>
            </Image>
            :
            <Image style={styles.img} source={{uri: row['img']}}/>
        }
      </View>
    );
  },


  _handlePress(param) {
    if (__DEV__) {
      console.log('press商品的：', param);
    }

    if (Platform.OS === 'ios') {
      //隐藏StatusBar
      StatusBarIOS.setHidden(true);
    }

    msg.emit('route:goToNext', {
      skuId: param.skuId,
      spuId: param.spuId,
      source: this.props.source,
      sceneName: 'GoodsDetails',
      sceneConfig: Navigator.SceneConfigs.FloatFromBottom
    });
  },


  /**
   * 跳转商品详情
   * @param param
   * @private
   */
  _handleDetail(param) {
    if (__DEV__) {
      console.log('press商品的：', param);
    }

    msg.emit('route:goToNext', {
      skuId: param.skuId,
      spuId: param.spuId,
      source: this.props.source,
      sceneName: 'ProductDetails',
      sceneConfig: Navigator.SceneConfigs.PushFromRight
    });
  },


  _handleHideModal() {
    msg.emit('cart:refresh');
    //刷新home采购单的数量
    msg.emit('refreshCartCount');
    msg.emit('route:backToLast');
  },

  /**
   * 获取数据后异步加载营销活动和价格
   * @param data
   * @private
   */
  _hanldDataReceive(data) {

    // 根据pageNum判断是否是刷新和下啦
    var resetData = data.pageNum == 0;

    // 默认为spu，为兼容收藏列表
    var getProductFlag = true;
    if (data.otherData) {
      getProductFlag = data.otherData.getProductFlag;
    }

    // 如果是spu列表，只查询区间价格
    if (getProductFlag) {

      var ids = "";
      data.dataList.forEach((v) => {
        ids += v.idStr + ";";
      });

      if(ids != "") {
        var productMarkets = this.state.markets;
        fetch(`${QMConst.HOST}/goods/markets?goodsIds=` + ids)
          .then((res) => {
            productMarkets = resetData ? res : productMarkets.concat(res);
            this.setState({
              markets: productMarkets
            });
          });

        var priceRange = this.state.priceRange;
        fetch(`${QMConst.HOST}/goods/priceRange`, {
          method: 'POST',
          body: JSON.stringify({
            goodsIds: ids
          })
        }).then((res) => {
          priceRange = resetData ? res : priceRange.concat(res);
          this.setState({
            priceRange: priceRange
          });
        });
      }
    }
    // 如果是sku列表，查询价格和营销活动
    else {

      var ids = "";
      data.dataList.forEach((v) => {
        ids += v.id + ",";
      });

      if(ids != "") {
        var markets = this.state.markets;
        fetch(`${QMConst.HOST}/goods/markets?goodsIds=` + ids)
          .then((res) => {
            markets = resetData ? res : markets.concat(res);
            this.setState({
              markets: markets
            });
          });

        var prices = this.state.prices;
        fetch(`${QMConst.HOST}/goods/prices?goodsIds=` + ids)
          .then((res) => {
            prices = resetData ? res : prices.concat(res);
            this.setState({
              prices: prices
            });
          });
      }
    }

    this.props.onDataReceive(data);
  },


  refreshListView() {
    this.refs.refreshListView.refreshListView();
  }
});


var styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff'
  },
  list: {
    flexWrap: 'wrap',
    flexDirection: 'row',
    backgroundColor: '#fff'
  },
  box: {
    width: (SCREEN_WIDTH-10)/2 - 10,
    justifyContent: 'center',
    marginTop: 8,
	  marginLeft: 10,
    borderWidth: 1 / PixelRatio.get(),
    borderColor: '#ebebeb',
    backgroundColor: '#FFF'
  },
  imgView: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
  },
  imgViewMargin: {
    margin: 5,
    flex: 1,
    backgroundColor: 'rgba(0, 0, 0, 0.3)',
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
  },
  imgViewText: {
    fontSize: 16,
    color: '#FFFFFF'
  },
  img: {
    height: (SCREEN_WIDTH-28)/2-2
  },
  detail: {
    flex: 1,
    padding: 8
  },
  proText: {
    fontSize: 14,
    height: 40,
    lineHeight: 20,
    color: '#333'
  },
  proText_disabled: {
    fontSize: 16,
    lineHeight: 20,
    height: 40,
    color: '#939495',
    overflow: 'hidden'
  },
  labelGroup: {
    flexDirection: 'row',
    paddingTop: 5
  },
  label: {
    paddingTop: 4,
    paddingRight: 8,
    paddingBottom: 4,
    paddingLeft: 8,
    marginRight: 5,
    borderRadius: 2
  },
  labelError: {
    backgroundColor: '#e17170'
  },
  labelInfo: {
    backgroundColor: '#66b5d6'
  },
  labelWarning: {
    backgroundColor: '#f4cb4b'
  },
  text: {
    fontSize: 10,
    color: '#fff'
  },
  proCart: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    paddingTop: 7
  },
  priceText: {
    fontSize: 18,
    lineHeight: 20,
    color: '#ff8a00'
  },
  cartImgContainer: {
    paddingRight: 10,
    backgroundColor: '#fff',
  },
  cart: {
    width: 24,
    height: 22
  }
});


module.exports = GoodsThumbnailList;
